package top.cardone.security.shiro.session.mgt.eis.impl;

import com.google.common.collect.Maps;
import lombok.Setter;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import top.cardone.cache.Cache;
import top.cardone.context.ApplicationContextHolder;

import java.io.Serializable;
import java.util.Collection;
import java.util.Map;

/**
 * @author yao hai tao
 * @date 16-2-2
 */
public class SessionDaoImpl extends AbstractSessionDAO {
    @Setter
    private String name = SessionDaoImpl.class.getName();

    private Map<Serializable, Session> activeSessions = Maps.newConcurrentMap();

    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = generateSessionId(session);

        assignSessionId(session, sessionId);

        this.update(session);

        activeSessions.put(sessionId, session);

        return sessionId;
    }

    @Override
    protected Session doReadSession(Serializable sessionId) {
        return ApplicationContextHolder.getBean(Cache.class).get(Session.class, this.name, sessionId);
    }

    @Override
    public void update(Session session) throws UnknownSessionException {
        ApplicationContextHolder.getBean(Cache.class).put(this.name, session.getId(), session);
    }

    @Override
    public void delete(Session session) {
        activeSessions.remove(session.getId());

        ApplicationContextHolder.getBean(Cache.class).evict(this.name, session.getId());
    }

    @Override
    public Collection<Session> getActiveSessions() {
        return activeSessions.values();
    }
}